#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Create by zhang
# Create on 2022/6/22 17:02
import time
from typing import List

from domain.report.common.period_enum import PeriodEnum
from infrastructure.common.threadingPool import ThreadPool
from domain.report.dto.balance_sheet_dto import BalanceSheetDTO, BalanceSheetSchema
from infrastructure.util.selenium_spider import RequestMethodEnum, SeleniumSpider2JsonConfiguration, spider2json


"""
https://xueqiu.com/snowman/S/SZ000063/detail#/ZCFZB
财务报表接口：https://stock.xueqiu.com/v5/stock/finance/cn/balance.json?symbol=SZ000063&type=all&is_detail=true&count=5&timestamp=1656172644203
"""



@ThreadPool(thread_name_prefix="xueqiu_")
def _balance_sheet_spider(stock_code:str, period:PeriodEnum=None, count:int=5):
    arr = stock_code.split(".")
    stock_code = f"{arr[1]}{arr[0]}"
    url = f"""
        https://stock.xueqiu.com/v5/stock/finance/cn/balance.json?symbol={stock_code}
        &type={"all" if period is None else f"Q{period.value}"}
        &is_detail=true&count={count}&timestamp={time.time()}
    """
    configuration = SeleniumSpider2JsonConfiguration()
    configuration.add_prepose_url(f"https://xueqiu.com/snowman/S/{stock_code}/detail#/ZCFZB", method=RequestMethodEnum.get)
    configuration.set_data_url(url)
    result = spider2json(configuration)
    return result


_xueqiuPeriod2_localPeriod = {
    "一季报": PeriodEnum.first_quarter,
    "中报": PeriodEnum.half_year,
    "三季报": PeriodEnum.three_quarter,
    "年报": PeriodEnum.year
}


def _spider_assembler(data:dict, stock_code, period: PeriodEnum) -> List[BalanceSheetDTO]:
    """
    未定位元素：current_assets_si， current_liab_si， frgn_currency_convert_diff,
    , noncurrent_assets_si, noncurrent_liab_si,, perpetual_bond,
    salable_financial_assets, othr_equity_instruments
    """
    dto_list = list()
    if data and len(data) > 0 and data.get("data", None) and data["data"].get("list", None):
        data_list = data["data"]["list"]
        for item in data_list:
            dto = BalanceSheetDTO()
            dto.stock_code = stock_code
            dto.stock_id = stock_code.split(".")[0]
            dto.year = int(item["report_name"][:3])
            dto.period = _xueqiuPeriod2_localPeriod[item["report_name"][4:]]
            BalanceSheetSchema.set(dto, "account_receivable", item["account_receivable"])
            BalanceSheetSchema.set(dto, "bills_receivable", item["bills_receivable"])
            BalanceSheetSchema.set(dto, "accounts_payable", item["accounts_payable"])
            BalanceSheetSchema.set(dto, "bill_payable", item["bill_payable"])
            BalanceSheetSchema.set(dto, "bond_payable", item["bond_payable"])
            BalanceSheetSchema.set(dto, "capital_reserve", item["capital_reserve"])
            BalanceSheetSchema.set(dto, "construction_in_process", item["construction_in_process_sum"])
            BalanceSheetSchema.set(dto, "contract_liabilities", item["contract_liabilities"])
            BalanceSheetSchema.set(dto, "contractual_assets", item["contractual_assets"])
            BalanceSheetSchema.set(dto, "money_cap", item["currency_funds"])
            BalanceSheetSchema.set(dto, "derivative_fnncl_liab", item["derivative_fnncl_liab"])
            BalanceSheetSchema.set(dto, "dev_expenditure", item["dev_expenditure"])
            BalanceSheetSchema.set(dto, "dividend_payable", item["dividend_payable"])
            BalanceSheetSchema.set(dto, "dividend_receivable", item["dividend_receivable"])
            BalanceSheetSchema.set(dto, "dt_assets", item["dt_assets"])
            BalanceSheetSchema.set(dto, "dt_liab", item["dt_liab"])
            BalanceSheetSchema.set(dto, "earned_surplus", item["surplus_rese"])
            BalanceSheetSchema.set(dto, "estimated_liab", item["estimated_liab"])
            BalanceSheetSchema.set(dto, "fixed_asset", item["fixed_asset"])
            BalanceSheetSchema.set(dto, "fixed_assets_disposal", item["fixed_asset"])
            BalanceSheetSchema.set(dto, "general_risk_provision", item["general_risk_provision"])
            BalanceSheetSchema.set(dto, "goodwill", item["goodwill"])
            BalanceSheetSchema.set(dto, "held_to_maturity_invest", item["held_to_maturity_invest"])
            BalanceSheetSchema.set(dto, "intangible_assets", item["intangible_assets"])
            BalanceSheetSchema.set(dto, "interest_payable", item["interest_payable"])
            BalanceSheetSchema.set(dto, "interest_receivable", item["interest_receivable"])
            BalanceSheetSchema.set(dto, "inventory", item["inventories"])
            BalanceSheetSchema.set(dto, "invest_property", item["invest_property_estate"])
            BalanceSheetSchema.set(dto, "lt_equity_invest", item["lt_eqt_invest"])
            BalanceSheetSchema.set(dto, "lt_loan", item["lt_loan"])
            BalanceSheetSchema.set(dto, "lt_payable", item["lt_payable"])
            BalanceSheetSchema.set(dto, "lt_receivable", item["lt_receivable"])
            BalanceSheetSchema.set(dto, "minority_equity", item["minority_equity"])
            BalanceSheetSchema.set(dto, "noncurrent_liab_di", item["noncurrent_liab_di"])
            BalanceSheetSchema.set(dto, "noncurrent_liab_due_in1y", item["noncurrent_liab_di"])
            BalanceSheetSchema.set(dto, "oil_and_gas_asset", item["oil_and_gas_assets"])
            BalanceSheetSchema.set(dto, "other_illiquid_fnncl_assets", item["other_illiquid_fnncl_assets"])
            BalanceSheetSchema.set(dto, "othr_compre_income", item["other_comprehensive_income"])
            BalanceSheetSchema.set(dto, "othr_current_assets", item["other_current_assets"])
            BalanceSheetSchema.set(dto, "othr_current_liab", item["other_current_liab"])
            BalanceSheetSchema.set(dto, "other_eq_ins_invest", item["other_eq_ins_invest"])
            BalanceSheetSchema.set(dto, "othr_non_current_liab", item["othr_noncurrent_liab"])
            BalanceSheetSchema.set(dto, "othr_noncurrent_assets", item["other_noncurrent_assets"])
            BalanceSheetSchema.set(dto, "othr_payables", item["other_payable"])
            BalanceSheetSchema.set(dto, "othr_receivables", item["other_receivable"])
            BalanceSheetSchema.set(dto, "payroll_payable", item["payroll_payable"])
            BalanceSheetSchema.set(dto, "pre_payment", item["pre_payment"])
            BalanceSheetSchema.set(dto, "pre_receivable", item["pre_receivable"])
            BalanceSheetSchema.set(dto, "productive_biological_assets", item["productive_biological_asset"])
            BalanceSheetSchema.set(dto, "project_goods_and_material", item["project_goods_and_material"])
            BalanceSheetSchema.set(dto, "saleable_finacial_assets", item["saleable_finacial_asset"])
            BalanceSheetSchema.set(dto, "shares", item["shares"])
            BalanceSheetSchema.set(dto, "special_payable", item["specific_payables"])
            BalanceSheetSchema.set(dto, "special_reserve", item["special_reserve"])
            BalanceSheetSchema.set(dto, "st_loan", item["st_loan"])
            BalanceSheetSchema.set(dto, "tax_payable", item["taxes_payable"])
            BalanceSheetSchema.set(dto, "to_sale_asset", item["to_sale_asset"])
            BalanceSheetSchema.set(dto, "to_sale_debt", item["to_sale_debt"])
            BalanceSheetSchema.set(dto, "total_assets", item["total_assets"])
            BalanceSheetSchema.set(dto, "total_assets", item["total_assets"])
            BalanceSheetSchema.set(dto, "total_current_assets", item["total_current_assets"])
            BalanceSheetSchema.set(dto, "total_current_liab", item["total_current_liab"])
            BalanceSheetSchema.set(dto, "total_holders_equity", item["total_holders_equity"])
            BalanceSheetSchema.set(dto, "total_liab", item["total_liab"])
            BalanceSheetSchema.set(dto, "total_liab_and_holders_equity", item["total_liab_and_holders_equity"])
            BalanceSheetSchema.set(dto, "total_noncurrent_assets", item["total_noncurrent_assets"])
            BalanceSheetSchema.set(dto, "total_noncurrent_liab", item["total_noncurrent_liab"])
            BalanceSheetSchema.set(dto, "total_quity_atsopc", item["total_parent_corp_equity"])
            BalanceSheetSchema.set(dto, "tradable_fnncl_assets", item["tradable_fnncl_assets"])
            BalanceSheetSchema.set(dto, "tradable_fnncl_liab", item["tradable_fnncl_liab"])
            BalanceSheetSchema.set(dto, "treasury_stock", item["treasury_share"])
            BalanceSheetSchema.set(dto, "undstrbtd_profit", item["undistr_porfit"])
            BalanceSheetSchema.set(dto, "dt_assets", item["deferred_income_tax_asset"])
            BalanceSheetSchema.set(dto, "dt_liab", item["deferred_income_tax_liab"])
            BalanceSheetSchema.set(dto, "lt_deferred_expense", item["lt_to_expense"])
            BalanceSheetSchema.set(dto, "nca_due_within_one_year", item["nca_within_1y"])
    return dto_list

def spider(stock_code:str, period:PeriodEnum=None, count:int=5) -> List[BalanceSheetDTO]:
    result = _balance_sheet_spider(stock_code, period, count)
    dtos = None
    if result and len(result) > 0:
        dtos = _spider_assembler(result, stock_code, period)
    return dtos